package com.bjpowernode.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.bjpowernode.constant.Constants;
import com.bjpowernode.entity.TClue;
import com.bjpowernode.entity.TCustomer;
import com.bjpowernode.entity.TUser;
import com.bjpowernode.entity.dto.TCustomerExcelDO;
import com.bjpowernode.mapper.TCustomerMapper;
import com.bjpowernode.query.TCustomerQuery;
import com.bjpowernode.service.TClueService;
import com.bjpowernode.service.TCustomerService;
import com.bjpowernode.utils.JwtUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class TCustomerServiceImpl implements TCustomerService {

    @Resource
    private TCustomerMapper tCustomerMapper;

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private TClueService tClueService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean saveCustomer(TCustomerQuery tCustomerQuery) {
        // 查询改线索id的数据 , 并判断状态
        TClue tClue = tClueService.selectClueById(tCustomerQuery.getClueId());
        if (tClue.getState() == -1) {
            throw new RuntimeException("该线索已经转换过客户");
        }


        // 转换保存操作
        // 创建
        TCustomer tCustomer = new TCustomer();
        // 转换
        BeanUtils.copyProperties(tCustomerQuery, tCustomer);
        // 赋值
        tCustomer.setCreateTime(DateTime.now());
        tCustomer.setEditTime(DateTime.now());
        String parseToken = jwtUtil.parseToken(tCustomerQuery.getJwt());
        TUser tUser = JSONUtil.toBean(parseToken, TUser.class);
        tCustomer.setCreateBy(tUser.getId());
        tCustomer.setEditBy(tUser.getId());
        int insert = tCustomerMapper.insertSelective(tCustomer);


        // 修改线索状态
        TClue updateTClue = new TClue();
        updateTClue.setId(tCustomerQuery.getClueId());
        updateTClue.setState(-1);
        int update = tClueService.updateClueState(updateTClue);
        return insert >= 1 && update >= 1;
    }

    @Override
    public PageInfo<TCustomer> getCustomerByPage(Integer current) {
        // 开启分页
        PageHelper.startPage(current, Constants.PAGE_SIZE);
        // 查询
        List<TCustomer> tCustomerList = tCustomerMapper.selectAllCustomerInfo();
        // 封装
        PageInfo<TCustomer> tCustomerPageInfo = new PageInfo<>(tCustomerList);
        // 返回
        return tCustomerPageInfo;
    }

    @Override
    public void batchExportExcel(ServletOutputStream outputStream , String ids) {
        // 判断ids是否有值
        List<Integer> idList = null;
        if (StringUtils.hasText(ids)) {
            // 非空
            String[] idsStringArray = ids.split(",");
            idList = Arrays.stream(idsStringArray)
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
        }
        // 获取数据
        List<TCustomer> tCustomerList = tCustomerMapper.selectAllCustomerInfoByIds(idList);
        List<TCustomerExcelDO> tCustomerExcelDOList = new ArrayList<>();
        // 遍历 : 将查询到的数据 转换到 TCustomerExcelDO 中去
        for (TCustomer tCustomer : tCustomerList) {
            TCustomerExcelDO tCustomerExcelDO = new TCustomerExcelDO();

            tCustomerExcelDO.setOwnerName(ObjectUtils.isEmpty(tCustomer.getOwnerDO().getName()) ? Constants.EMPTY : tCustomer.getOwnerDO().getName());
            tCustomerExcelDO.setActivityName(ObjectUtils.isEmpty(tCustomer.getActivityDO().getName()) ? Constants.EMPTY : tCustomer.getActivityDO().getName());
            tCustomerExcelDO.setAppellationName(tCustomer.getAppellationDO().getTypeValue());
            tCustomerExcelDO.setFullName(tCustomer.getClueDO().getFullName());
            tCustomerExcelDO.setPhone(tCustomer.getClueDO().getPhone());
            tCustomerExcelDO.setWeixin(tCustomer.getClueDO().getWeixin());
            tCustomerExcelDO.setQq(tCustomer.getClueDO().getQq());
            tCustomerExcelDO.setEmail(tCustomer.getClueDO().getEmail());
            tCustomerExcelDO.setAge(tCustomer.getClueDO().getAge());
            tCustomerExcelDO.setJob(tCustomer.getClueDO().getJob());
            tCustomerExcelDO.setYearIncome(tCustomer.getClueDO().getYearIncome());
            tCustomerExcelDO.setAddress(tCustomer.getClueDO().getAddress());
            tCustomerExcelDO.setNeedLoanName(tCustomer.getNeedLoanDO().getTypeValue());
            tCustomerExcelDO.setIntentionStateName(tCustomer.getIntentionStateDO().getTypeValue());
            tCustomerExcelDO.setProduct(ObjectUtils.isEmpty(tCustomer.getProductDO().getName()) ? Constants.EMPTY : tCustomer.getProductDO().getName());
            tCustomerExcelDO.setStateName(tCustomer.getStateDO().getTypeValue());
            tCustomerExcelDO.setSourceName(tCustomer.getSourceDO().getTypeValue());
            tCustomerExcelDO.setNextContactTime(tCustomer.getNextContactTime());
            tCustomerExcelDO.setDescription(tCustomer.getDescription());

            tCustomerExcelDOList.add(tCustomerExcelDO);
        }

        EasyExcel.write(outputStream, TCustomerExcelDO.class)
                .sheet("模板")
                .doWrite(tCustomerExcelDOList);
    }

    @Override
    public TCustomer loadCustomerDetail(Integer id) {
        TCustomer tCustomer = tCustomerMapper.selectInfoById(id);
        return tCustomer;
    }
}
